/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package percussiongenerator.sound;

import java.util.ArrayList;
import org.jfonia.model.ToneSequence;
import percussiongenerator.model.Track;

/**
 *
 * @author Jannes Plyson
 */
public class MidiPlayerNoLoop extends MidiPlayerTimer{
    
    protected void addTimerEvents(){
        ArrayList<Track> tracks = trackCollection.getTracks();
        long newLastAdded = (System.nanoTime()-lastStarted) + 2000000*interval;
        for(int i = 0; i < tracks.size(); i++){
            Track track = tracks.get(i);
            if(!track.isMuted()){
                long time = lastAdded % track.getPerformanceLength();
                long newTime = newLastAdded % track.getPerformanceLength();
                ToneSequence seq = track.getStaff().getToneSequence();
                if(seq != null){
                    if(newLastAdded > track.getPerformanceLength()){
                        stop();
                    }else{
                        int pos = seq.indexOf(seq.getPerformanceNode(time+1));
                        if(seq.getPerformanceNodeFromIndex(pos).getBegin() <= lastAdded){
                            pos++;
                        }
                        if(newTime < time){ //end border crossed -> loop
                            //add events before end of border.
                            while(pos < seq.size()){
                                scheduleNote(seq.getPerformanceNodeFromIndex(pos),seq , track.getInstrument());
                                pos++;
                            }
                            pos = 0;
                        }
                        //add events from pos until newLastAdded.
                        while(pos < seq.size() && seq.getPerformanceNodeFromIndex(pos).getBegin() < newTime){
                            scheduleNote(seq.getPerformanceNodeFromIndex(pos),seq , track.getInstrument());
                            pos++;
                        }
                    }
                }
            }
        }
        lastAdded = newLastAdded;
    }
}
